// src/store/Appointment/appointment.js
import axios from "axios"

const api = axios.create({
  baseURL: 'http://localhost:8000', // 根据您的后端地址修改
  timeout: 7000,
  headers: {
    'Content-Type': 'application/json'
  }
})

const state = {

}

const mutations = {
    SET_TOKEN(state, token) {
        state.token = token
        if (token){
            localStorage.setItem('access_token', token)
        }else{
            localStorage.removeItem('access_token')
        }
    },
    SET_USERID(state, userid) {
        state.userid = userid
        if (userid) {
            localStorage.setItem('user_id', userid)
        } else {
            localStorage.removeItem('user_id')
        }
    },
    SET_USERNAME(state, username) {
        state.username = username
         if (username) {
            localStorage.setItem('user_name', username)
        } else {
            localStorage.removeItem('user_name')
        }
    },
    SET_ROLE(state, role) {
        state.role = role
        if (role) {
            localStorage.setItem('role', role)
        } else {
            localStorage.removeItem('role')
        }
    },
    CLEAR_AUTH(state) {
        state.token = ''
        state.userid = ''
        state.username = ''
        localStorage.removeItem('access_token')
        localStorage.removeItem('user_id')
        localStorage.removeItem('user_name')
        localStorage.removeItem('role')
    }
}

const actions = {
    async login({ commit }, loginForm) {
        // 登录逻辑
        try {
            const response = await api.post('/login/login', loginForm)
            // console.log( response)
            // 提交多个 mutations
             if (response.data.access_token) {
                commit('SET_TOKEN', response.data.access_token)
            }

            if (response.data.role) {
                commit('SET_USERNAME', response.data.username)
            }
            if (response.data.userid) {
                commit('SET_USERID', response.data.userid)
            }
            if (response.data.role) {
                commit('SET_ROLE', response.data.role)
            }

            // 返回响应数据供组件使用
            return response.data
        } catch (error) {
            console.error("登录失败：", error)
            throw error
        }
    },

    // 登出功能
    logout({ commit }) {
        commit('CLEAR_AUTH')

        // 如果需要调用后端登出接口，可以在这里添加
    }
}

const getters = {
    isAuthenticated: state => !!state.token,
    username: state => state.username,
    userid: state => state.userid,
    token: state => state.token
}

// 添加 namespaced 属性，使模块具有命名空间
export default {
    namespaced: true, // 启用命名空间
    state,
    mutations,
    actions,
    getters
}
